import os,shutil
import z_combine_images,class_mysql

def get_paths(directory):
    paths = []
    for file in os.listdir(directory):
        path=os.path.join(directory,file)
        if os.path.isdir(path):
            path=path.replace('\\','/')
            paths.append(path)
    return paths
# 初始化查询对象
db = class_mysql.MySQLQuery(host="192.168.10.81", user="root", password="", database="xiaocheng")
db.connect()


paths= get_paths("D:/Desk/TEMU-批量上款/1-内容分组")



for path in paths:
  pics=os.listdir(path)
  # 文件数量验证
  values=['主图','方图','前','后','详情1','详情2','pic']
  for value in values:
    tag=0
    for pic in pics:
      if value in pic:
        tag=1
    if tag==0:
      path_new="D:/Desk/TEMU-批量上款/4-错误/"+'文件缺失#'+path.split('/')[-1]
      print("文件缺失#"+path.split('/')[-1])
      shutil.move(path,path_new)
  # 模特款号与快卖SKU验证
  model_name=(path.split('/')[-1]).split('_')[0]
  temp_dict=db.fetch_one("select style_name from data_model where name='"+model_name+"'")
  style_name=temp_dict['style_name']
  if style_name==None:
    path_new="D:/Desk/TEMU-批量上款/4-错误/"+'款号错误#'+path.split('/')[-1]
    shutil.move(path,path_new)
  else:
    temp_dict=db.fetch_one("select count(*) from data_kuaimai_operater_number where operater_number like '%A7%'")
    count_A7=temp_dict['count(*)']
    operater_number='A'+str(70000+count_A7+1)
    db.insert_data("data_kuaimai_operater_number",{'operater_number':operater_number})

    for pic in pics:
      if 'pic' not in pic:
        if not os.path.exists("D:/Desk/TEMU-批量上款/3-上架图包/"+operater_number):
          os.makedirs("D:/Desk/TEMU-批量上款/3-上架图包/"+operater_number)
        path_new="D:/Desk/TEMU-批量上款/3-上架图包/"+operater_number+'/'+pic
        shutil.copy(path+'/'+pic,path_new)
      else:
        if not os.path.exists("D:/Desk/TEMU-批量上款/2-快麦图包/"+style_name.split('#')[0]):
          os.makedirs("D:/Desk/TEMU-批量上款/2-快麦图包/"+style_name.split('#')[0])
        path_new="D:/Desk/TEMU-批量上款/2-快麦图包/"+style_name.split('#')[0]+'/'+operater_number+'.png'
        shutil.copy(path+'/'+pic,path_new)
    path_front=path+'/'+'前.jpg'
    path_back=path+'/'+'后.jpg'
    path_result="D:/Desk/TEMU-批量上款/2-快麦图包/"+style_name.split('#')[0]+'/'+'（图）'+style_name.split('#')[0]+'%'+style_name.split('#')[1]+'+'+operater_number+'.png'
    try:
      z_combine_images.combine_images_with_title(path_front,path_back,path_result)
    except:
      print(os.basename(path),'合成失败')